#include <stdlib.h>
#include <string.h>
#include "sequence-stack.h"

int InitStack(SeqStack *stack){
    if (stack == NULL){
        return(-1);
    }else{
        stack->data = malloc(1 * sizeof(ElemType));
        stack->top = 0;
        stack->capacity = 1;
        return (0);
    }
}

int DestroyStack(SeqStack *stack){
    if (stack == NULL || stack->data == NULL){
        return(-1);
    } else{
        free(stack->data);
        stack->data = NULL;
        stack->capacity = 0;
        stack->top = 0;
        return(0);
    }
}

int ClearStack(SeqStack *stack){
    if (stack == NULL || stack->data == NULL){
        return(-1);
    }else {
        stack->top = 0;
        memset(stack->data, 0, sizeof(ElemType));
        return (0);
    }
}

int StackEmpty(SeqStack stack){
    if (stack.data == NULL && stack.capacity == 0 && stack.top == 0){
        return(1);
    } else if (stack.data == NULL || stack.capacity == 0){
        return(-1);
    } else{
        return(0);
    }
}

int GetTop(SeqStack stack,ElemType *e){
    if (stack.capacity == 0 || stack.data == NULL){
        return(-1);
    }else{
        memcpy(e,&stack.data[stack.top], sizeof(ElemType));
        return(0);
    }
}

int Push(SeqStack *stack,ElemType e){
    if (stack == NULL || stack->data == NULL){
        return(-1);
    }else{
        if(stack->top == (stack->capacity-1)){
            stack->capacity = 2*stack->capacity;
            stack->data = realloc(stack->data, stack->capacity*sizeof(ElemType));
        }
        memcpy(&stack->data[++stack->top],&e,sizeof(ElemType));
        return(0);
    }
}

int Pop(SeqStack *stack,ElemType *e){
    if (stack == NULL || stack->data == NULL){
        return(-1);
    }else{
        memcpy(e,&stack->data[stack->top--],sizeof(ElemType));  //It is easy to cross the boundary here.
                                                                // In order to be consistent with the assembly stack, it is not processed
        return(0);
    }
}

int StackLength(SeqStack stack){
    if (stack.top == 0 && stack.data == NULL){
        return(0);
    } else if (stack.capacity == 0  || stack.data == NULL){
        return(-1);
    } else{
        return(stack.top+1);
    }
}